package com.example.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Component
@Slf4j
public class JWTUTils {
    private static final long EXPIRE = 30*60 * 1000; //过期时间

    public static final String singKey = "supermarket";//密钥，动态生成的密钥

    /**
     * 生成token
     * @param claims  要传送消息map
     * @return
     */
    public static String generate(Map<String,Object> claims) {
        Date nowDate = new Date();
        //过期时间,设定为一分钟
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE);

        return Jwts.builder()
                .setClaims(claims)  //自定义claims
                .setIssuedAt(nowDate)//当前时间
                .setExpiration(expireDate) //过期时间
                .signWith(SignatureAlgorithm.HS256,singKey)//签名算法和key
                .compact();
    }



    //校验jwt
    public static Claims parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(singKey)
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }


}
